import re
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator


class CSRFExemptMiddleware:
    """
    自定义中间件，用于豁免特定URL的CSRF保护
    """
    
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        # 检查请求路径是否在豁免列表中
        if hasattr(settings, 'CSRF_EXEMPT_URLS'):
            for pattern in settings.CSRF_EXEMPT_URLS:
                if re.match(pattern, request.path):
                    # 为豁免的URL设置csrf_exempt标记
                    request._dont_enforce_csrf_checks = True
                    break
                    
        response = self.get_response(request)
        return response
